<template>
  <div class="activity-list-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="活动状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="finished" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="活动类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择类型"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="篮球" value="basketball" />
            <el-option label="羽毛球" value="badminton" />
            <el-option label="足球" value="football" />
            <el-option label="网球" value="tennis" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="handleCreate">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            创建活动
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedIds.length"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出数据
          </el-button>
        </div>

        <div class="toolbar-right">
          <el-tooltip content="刷新" placement="top">
            <el-button circle @click="handleRefresh">
              <IconifyIconOffline icon="ep:refresh" />
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 活动列表表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="活动封面" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.cover"
              :preview-src-list="[row.cover]"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="name"
          label="活动名称"
          min-width="200"
          show-overflow-tooltip
        />

        <el-table-column label="活动类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{
              getTypeName(row.type)
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="活动状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{
              getStatusName(row.status)
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="maxParticipants" label="报名人数" width="120">
          <template #default="{ row }">
            <span>{{ row.currentParticipants }}/{{ row.maxParticipants }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="fee" label="活动费用" width="100">
          <template #default="{ row }">
            <span v-if="row.fee > 0" class="text-red-500">¥{{ row.fee }}</span>
            <span v-else class="text-green-500">免费</span>
          </template>
        </el-table-column>

        <el-table-column prop="startTime" label="开始时间" width="180" />

        <el-table-column prop="endTime" label="结束时间" width="180" />

        <el-table-column prop="creator" label="创建者" width="120" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              <IconifyIconOffline icon="ep:view" class="mr-1" />
              查看
            </el-button>
            <el-button link type="primary" @click="handleEdit(row)">
              <IconifyIconOffline icon="ep:edit" class="mr-1" />
              编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <IconifyIconOffline icon="ep:delete" class="mr-1" />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: "",
  status: "",
  type: "",
  dateRange: []
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedIds = ref([]);

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 模拟数据
const mockData = [
  {
    id: 1,
    name: "春季篮球赛",
    type: "basketball",
    status: "active",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=basketball%20game%20poster&image_size=landscape_4_3",
    maxParticipants: 100,
    currentParticipants: 68,
    fee: 50,
    startTime: "2024-03-01 09:00:00",
    endTime: "2024-03-15 18:00:00",
    creator: "张三"
  },
  {
    id: 2,
    name: "羽毛球友谊赛",
    type: "badminton",
    status: "pending",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=badminton%20tournament%20poster&image_size=landscape_4_3",
    maxParticipants: 50,
    currentParticipants: 32,
    fee: 0,
    startTime: "2024-03-20 14:00:00",
    endTime: "2024-03-20 18:00:00",
    creator: "李四"
  },
  {
    id: 3,
    name: "足球联赛",
    type: "football",
    status: "finished",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=football%20league%20championship&image_size=landscape_4_3",
    maxParticipants: 200,
    currentParticipants: 180,
    fee: 100,
    startTime: "2024-02-01 10:00:00",
    endTime: "2024-02-28 17:00:00",
    creator: "王五"
  }
];

// 获取活动类型名称
const getTypeName = (type: string) => {
  const typeMap = {
    basketball: "篮球",
    badminton: "羽毛球",
    football: "足球",
    tennis: "网球"
  };
  return typeMap[type] || type;
};

// 获取活动类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    basketball: "warning",
    badminton: "success",
    football: "primary",
    tennis: "info"
  };
  return typeMap[type] || "";
};

// 获取状态名称
const getStatusName = (status: string) => {
  const statusMap = {
    pending: "未开始",
    active: "进行中",
    finished: "已结束",
    cancelled: "已取消"
  };
  return statusMap[status] || status;
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    pending: "info",
    active: "success",
    finished: "warning",
    cancelled: "danger"
  };
  return statusMap[status] || "";
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    status: "",
    type: "",
    dateRange: []
  });
  handleSearch();
};

// 创建活动
const handleCreate = () => {
  router.push("/activity/create");
};

// 查看活动
const handleView = (row: any) => {
  router.push(`/activity/detail/${row.id}`);
};

// 编辑活动
const handleEdit = (row: any) => {
  router.push(`/activity/edit/${row.id}`);
};

// 删除活动
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除活动"${row.name}"吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 这里应该调用删除API
    ElMessage.success("删除成功");
    fetchData();
  } catch {
    // 用户取消删除
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个活动吗？`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用批量删除API
    ElMessage.success("批量删除成功");
    selectedIds.value = [];
    fetchData();
  } catch {
    // 用户取消删除
  }
};

// 导出数据
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 刷新
const handleRefresh = () => {
  fetchData();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  fetchData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchData();
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));

    // 这里应该调用真实的API
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="scss">
.activity-list-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.toolbar-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  .el-form-item {
    margin-bottom: 0;
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-red-500 {
  color: #f56c6c;
}

.text-green-500 {
  color: #67c23a;
}

@media (max-width: 768px) {
  .activity-list-container {
    padding: 10px;
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .toolbar-left {
    justify-content: center;
  }
}
</style>
